-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

-- eeprom 模型
-- 支持offsetwidth: 1, 2, 4
-- 数据大小：任意
-- 支持生成指定大小的数据文件，默认size为1024
local instance = {
    offset_width = 1,
    size = 1024 -- 大小为1024
}

local log = require "log"
local cjson = require "cjson"
local commonI2c_instance = require "protocol.commonI2c_instance"
local bin_parser_instance = require "data.BinParser"

function instance:new(obj, offset_width, size)
    obj = obj or {}
    setmetatable(obj, self)
    self.__index = self
    self.offset_width = offset_width
    self.size = size
    return obj
end

local parser_instance = {
    prot_parser = {},
    data_parser = {},
}

function parser_instance:new(obj, prot_parser, data_parser)
    obj = obj or {}
    setmetatable(obj, self)
    self.__index = self
    self.prot_parser = prot_parser
    self.data_parser = data_parser
    return obj
end

function parser_instance:read_data(length)
    local offset = self.prot_parser:parse_offset()
    return self.data_parser:read_data(offset, length)
end

function parser_instance:write_data()
    local offset = self.prot_parser:parse_offset()
    local data = self.prot_parser:parse_data()

    log:print(LOG_ERROR, "eeprom write_data offset is %d", offset)
    log:print(LOG_ERROR, "eeprom write_data data is %s", cjson.encode(data))

    self.data_parser:write_data(offset, data)
end

function instance:read(tx_buffer, length, filename)
    if type(tx_buffer) ~= "table" or #tx_buffer < 2 then    -- 2: 读命令时传输数据的最小长度
        log:print(LOG_ERROR, "tx_buffer length(%d) error", #tx_buffer)
        return
    end
    local common_i2c = commonI2c_instance:new(nil, tx_buffer, self.offset_width)
    local bin_parser = bin_parser_instance:new(nil, filename, self.size)

    local parser = parser_instance:new(nil, common_i2c, bin_parser)
    return parser:read_data(length)
end

function instance:write(tx_buffer, filename)
    if type(tx_buffer) ~= "table" or #tx_buffer < 3 then    -- 3: 写命令时传输数据的最小长度
        log:print(LOG_ERROR, "tx_buffer length(%d) error", #tx_buffer)
        return
    end

    log:print(LOG_ERROR, "write eeprom get tx_buffer is %s", cjson.encode(tx_buffer))
    local common_i2c = commonI2c_instance:new(nil, tx_buffer, self.offset_width)
    local bin_parser = bin_parser_instance:new(nil, filename, self.size)

    local parser = parser_instance:new(nil, common_i2c, bin_parser)
    parser:write_data()
end

return instance
